﻿using Kongt.IServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Kongt.ServiceProvider
{
    public class ServiceFactory
    {
        /// <summary>
        /// 生产服务接口的实现
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
		public static T Create<T>() where T : IService
        {
            T create = default(T);
            if (HttpContext.Current != null)
            {
                List<IService> item = HttpContext.Current.Session["_serviceInstace"] as List<IService>;
                if (item != null)
                {
                    create = (T)item.FirstOrDefault(t => t.GetType().GetInterfaces().Contains(typeof(T)));
                    if (create == null)//从session中没有服务实例，创建一个
                    {
                        create = Instance<T>.Create;
                        item.Add(create);
                    }
                }
                else//没有session
                {
                    create = Instance<T>.Create;
                    item = new List<IService>()
                    {
                       create
                    };
                }
                HttpContext.Current.Session["_serviceInstace"] = item;
                return create;
            }
            else
            {
                return Instance<T>.Create;
            }
        }
    }
}


